import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import { getToken } from '@/common/token'
import NProgress from 'nprogress'
import menu from '@/store/modules/menu'
import { getFrontToken } from '@/common/token'
NProgress.configure({
    showSpinner: false,
})
const whiteList = ['/login', '/404', '/agreement', '/agreement/privacy', '/mmcLogin', '/mmcLogin/course_list', "/mmcLogin/course_schedule", "/mmcLogin/download", '/mmcLogin/video', '/mmcLogin/image', '/h5']
router.beforeEach((to, from, next) => {
    NProgress.start()
    if (getToken()) {
        if (to.path === '/login') {
            next({
                path: '/',
            })
            NProgress.done()
        } else {
            //console.log(store.state.member.perms);
            if (store.state.member.perms.length === 0) {
                store.dispatch('GetInfo')
                    .then((res) => {
                        store.dispatch('GenerateRoutes').then((accessRoute) => {
                            router.addRoutes(accessRoute)
                            next({ ...to, replace: true })
                        })
                    })
                    .catch((err) => {
                        console.log('登录失败', err)
                        store.dispatch('loginOut').then((err) => {
                            Message.error(err)
                            next({
                                path: '/login',
                            })
                        })
                    })
            } else {
                next()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            let user_type = getFrontToken('user_type')
            if (user_type == 2) {
                next(`/mmcLogin?redirect=${to.fullPath}`)
            } else {
                next(`/login?redirect=${to.fullPath}`)
            }
            NProgress.done()
        }
    }
})
router.afterEach(() => {
    NProgress.done()
})
